package com.ruoyi.ai.controller;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.qywx.domain.SysQywxChatdata;
import com.ruoyi.qywx.service.ISysQywxChatdataService;
import com.ruoyi.system.service.impl.SysAIServiceImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.ai.domain.SysAiTasks;
import com.ruoyi.ai.service.ISysAiTasksService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * AI任务Controller
 *
 * @author yaolei
 * @date 2024-06-23
 */
@RestController
@RequestMapping("/ai/tasks")
public class SysAiTasksController extends BaseController
{
    @Autowired
    private ISysAiTasksService sysAiTasksService;
    @Autowired
    private ISysQywxChatdataService sysQywxChatdataService;
    /**
     * 查询AI任务列表
     */
    @PreAuthorize("@ss.hasPermi('ai:tasks:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysAiTasks sysAiTasks)
    {
        startPage();
        Map<String, Object> params =  sysAiTasks.getParams();
        if(!"".equals((String)params.get("beginMsgtime")) && params.get("beginMsgtime")!=null){
            String dateString = (String)params.get("beginMsgtime") + " 00:00:00";
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(dateString);
                //Timestamp timestamp = new Timestamp(date.getTime());
                params.replace("beginMsgtime", Long.toString(date.getTime()));
                System.out.println(date.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if(!"".equals((String)params.get("endMsgtime")) && params.get("endMsgtime")!=null){
            String dateString = (String)params.get("endMsgtime") + " 23:59:59";
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(dateString);
                //Timestamp timestamp = new Timestamp(date.getTime());
                params.replace("endMsgtime", Long.toString(date.getTime()));
                System.out.println(date.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        sysAiTasks.setParams(params);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //sysAiTasks.setOrignalMsg(user.getRemark());
        sysAiTasks.setTaskOwner(user.getRemark());
        System.out.println("sysAiTasksList=======" + JSON.toJSONString(sysAiTasks));
        List<SysAiTasks> list = sysAiTasksService.selectSysAiTasksList(sysAiTasks);
        return getDataTable(list);
    }

    /**
     * 导出AI任务列表
     */
    @PreAuthorize("@ss.hasPermi('ai:tasks:export')")
    @Log(title = "AI任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysAiTasks sysAiTasks)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //sysAiTasks.setOrignalMsg(user.getRemark());
        sysAiTasks.setTaskOwner(user.getRemark());
        List<SysAiTasks> list = sysAiTasksService.selectSysAiTasksList(sysAiTasks);
        //对list  进行处理
        for(int i=0;i<list.size();i++){
            Timestamp timestamp = new Timestamp(list.get(i).getMsgtime());
            Date currentDate = new Date(timestamp.getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = sdf.format(currentDate);
            list.get(i).setMsgtimeStr(formattedDate);

            list.get(i).setTaskMemo(cleanStr(list.get(i).getTaskMemo()));
            list.get(i).setTaskDate(cleanStr(list.get(i).getTaskDate()));
            list.get(i).setTaskTime(cleanStr(list.get(i).getTaskTime()));
            list.get(i).setTaskUserlist(cleanStr(list.get(i).getTaskUserlist()));
            list.get(i).setTaskKeyword(cleanStr(list.get(i).getTaskKeyword()));
            list.get(i).setTaskAddress(cleanStr(list.get(i).getTaskAddress()));
            list.get(i).setTaskIsProblem(cleanStr(list.get(i).getTaskIsProblem()));
            list.get(i).setTaskProblem(cleanStr(list.get(i).getTaskProblem()));
            list.get(i).setTaskIsResult(cleanStr(list.get(i).getTaskIsResult()));
            list.get(i).setTaskResult(cleanStr(list.get(i).getTaskResult()));
            list.get(i).setTaskIsSolution(cleanStr(list.get(i).getTaskIsSolution()));
            list.get(i).setTaskSolution(cleanStr(list.get(i).getTaskSolution()));
            list.get(i).setTaskRes(cleanStr(list.get(i).getTaskRes()));
            list.get(i).setTaskTerms(cleanStr(list.get(i).getTaskTerms()));
            list.get(i).setTaskTargets(cleanStr(list.get(i).getTaskTargets()));

            //处理行动项
            list.get(i).setTaskDetail(splitJson(list.get(i).getTaskDetail()));

        }


        ExcelUtil<SysAiTasks> util = new ExcelUtil<SysAiTasks>(SysAiTasks.class);
        util.hideColumn("taskOrignalJson", "orignalMsg", "isMeeting", "msgtime");
        util.hideColumn("taskOrignalJson", "orignalMsg", "isMeeting", "msgtime");
        //util.hideColumn("orignalMsg");
        //util.hideColumn("isMeeting");

        util.exportExcel(response, list, "AI任务数据");
    }

    public String cleanStr(String content){
        if(content != null){
            if(content.equals("无")){
                return "";
            }
            if(content.equals("[]")){
                return "";
            }
        }
        return content;
    }

    public String splitJson(String content){
        //content = "[{\"行动项\":\"参加产品会\"}]";
        String result = "";
        try {
            JSONArray jsonArray = JSONArray.parseArray(content);
            for (int i=0;i<jsonArray.size();i++){
                try {
                    JSONObject jsonChatdata = JSONObject.parseObject(jsonArray.get(i).toString());
                    result = result + "◆" + jsonChatdata.getString("行动项") + "\n";
                }catch (Exception ex3){
                    result = result + "◆" + jsonArray.get(i).toString() + "\n";
                }
            }

        }catch (Exception ex1){

            try {
                JSONObject jsonChatdata = JSONObject.parseObject(content);
                result = result + "◆" + jsonChatdata.getString("行动项") + "\n";

            }catch (Exception ex2) {
                result = content;
            }
        }

        return result;
    }

    /**
     * 获取AI任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('ai:tasks:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysAiTasksService.selectSysAiTasksById(id));
    }

    /**
     * 新增AI任务
     */
    @PreAuthorize("@ss.hasPermi('ai:tasks:add')")
    @Log(title = "AI任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysAiTasks sysAiTasks)
    {
        return toAjax(sysAiTasksService.insertSysAiTasks(sysAiTasks));
    }

    /**
     * 修改AI任务
     */
    @PreAuthorize("@ss.hasPermi('ai:tasks:edit')")
    @Log(title = "AI任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysAiTasks sysAiTasks)
    {
        sysAiTasks.setIsEdit(1);//设置为 已编辑过
        return toAjax(sysAiTasksService.updateSysAiTasks(sysAiTasks));
    }

    /**
     * 删除AI任务
     */
    @PreAuthorize("@ss.hasPermi('ai:tasks:remove')")
    @Log(title = "AI任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysAiTasksService.deleteSysAiTasksByIds(ids));
    }


    /**
     * 新增AI任务
     */
    @PreAuthorize("@ss.hasPermi('ai:tasks:edit')")
    @Log(title = "AI任务重新分析", businessType = BusinessType.INSERT)
    @PostMapping("/retask")
    public AjaxResult retask(@RequestBody SysAiTasks sysAiTasks) throws ParseException {
        String newDateStr = sysAiTasks.getTaskDate();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long beginMsgtime = (format.parse(newDateStr+" 00:00:00")).getTime();
        Long endMsgtime = (format.parse(newDateStr+" 23:59:59")).getTime();


        try {
            format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = format.parse(newDateStr);

            //开始更新内啥
            Map<String, Object> params =  new HashMap<String, Object>();
            params.put("beginMsgtime", beginMsgtime);
            params.put("endMsgtime", endMsgtime);

            //再查询当日待处理信息
            SysQywxChatdata paramSysQywxChatdata =  new SysQywxChatdata();
            paramSysQywxChatdata.setDecryptChatMsg("zhangliang");
            paramSysQywxChatdata.setParams(params);
            List<SysQywxChatdata> sysQywxChatdataList = sysQywxChatdataService.selectSysQywxChatdataList(paramSysQywxChatdata);

            //设置某任务 未处理
            SysQywxChatdata tmpSysQywxChatdata = sysQywxChatdataList.get(0);
            tmpSysQywxChatdata.setIsHandled(0L);
            sysQywxChatdataService.updateSysQywxChatdata(tmpSysQywxChatdata);

            //开始异步
            CompletableFuture.supplyAsync(() -> {
                try {
                    SysAIServiceImpl.taskListMergeHandled(date);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "Hello";
            }).thenAccept(result -> System.out.println("Result: " + result));
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        return toAjax(1);
    }

}
